package com.example.myapplication.types;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.myapplication.base.BaseActivity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class TypeTestActivity extends BaseActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        setContentView(textView);

        textView.setText("Hello, World!");

        textView.setOnClickListener(this::onClick);
    }

    private void onClick(View view) {

        Test<String> test = new Test<>();

        Class<?> clazz = analysisClassInfo(test);
        if (clazz != Void.class) {
            toast(clazz);
        }
    }

    private Class<?> analysisClassInfo(Object object) {
        //getGenericSuperclass()得到包含原始类型，参数化，数组，类型变量，基本数据
        Type getType = object.getClass().getGenericSuperclass();
        //获取参数化类型
        try {
            Type[] params = ((ParameterizedType) getType).getActualTypeArguments();
            return (Class<?>) params[0];
        } catch (Exception e) {
            e.printStackTrace();
            toast("获取泛型类型错误" + e.getMessage());
        }
        return Void.class;
    }


    private void toast(Object text) {
        Toast.makeText(this, String.valueOf(text), Toast.LENGTH_SHORT).show();
    }

}